import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getFilesList } from '@/api/files.js'

export const useDocsStore = defineStore('docs', () => {
  const docs = ref([])
  const loading = ref(false)
  const groupedDocs = ref([])
  const needsRefresh = false // 标志是否需要刷新

  async function fetchDocs() {
    loading.value = true
    try {
      const response = await getFilesList()
      docs.value = await response.items

      const tagMap = new Map()
      for (const doc of docs.value) {
        for (const tag of doc.tags || []) {
          if (!tagMap.has(tag.name)) {
            tagMap.set(tag.name, {
              id: `tag_${tag.id}`,
              label: '🏷️ ' + tag.name,
              children: [],
            })
          }
          tagMap.get(tag.name).children.push({
            id: doc.id,
            label: doc.name,
            isDoc: true,
            raw: doc,
          })
        }
      }

      groupedDocs.value = Array.from(tagMap.values())
    } catch (error) {
      console.error('加载文档失败', error)
    } finally {
      loading.value = false
    }
  }

  function triggerRefresh() {
    this.needsRefresh = true
  }

  return {
    groupedDocs,
    loading,
    needsRefresh,
    fetchDocs,
    triggerRefresh,
  }
})
